import os
import json
from celery import Celery
from markitdown import MarkItDown
from openai import OpenAI
from email.message import EmailMessage
import smtplib
import markdown
#import logging
from backend.utils import settings

# Celery 配置
celery_app = Celery(
    'tasks',
    broker=os.getenv('CELERY_BROKER_URL', 'redis://redis:6379/0'),
    backend=os.getenv('CELERY_RESULT_BACKEND', 'redis://redis:6379/0')
)

# 初始化 LLM 客户端
visual_client = OpenAI(api_key=settings.visual_token, base_url=settings.visual_base_url)
text_client   = OpenAI(api_key=settings.compliance_token, base_url=settings.compliance_base_url)

@celery_app.task
def process_document(file_path: str, filename: str, email: str, doc_name: str):
    try:
        # 1. 转换为 Markdown
        #md = MarkItDown(llm_client=visual_client, llm_model=settings.visual_model_id)

        md = MarkItDown(
            llm_client=visual_client,
            llm_model=settings.visual_model_id,
            llm_prompt="分析这张图片的类型（地图/商标/文字/纯图案），简要的输出形式参考:'这张图片疑似是中国地图'、'腾讯的Logo'、'图片包含的文字是:'、'图案无内容'"
        )
        try:
            result = md.convert(file_path)
            markdown_content = result.text_content
        except Exception as e:
            print(f"异常: {file_path} - {str(e)}")            

        # 2. 准备合规提示词，去除所有控制字符，保证单行 JSON
        raw_prompt = settings.compliance_prompt
        cleaned    = raw_prompt.replace('\n', ' ').replace('\r', ' ')
        prompt     = json.loads(cleaned)
        prompt['content'] += f"\n文档内容：\n{markdown_content}"

        # 3. 调用合规模型
        resp = text_client.chat.completions.create(
            model=settings.compliance_model_id,
            messages=[prompt]
        )
        table_md = resp.choices[0].message.content

        # 4. 构造邮件
        subject   = f"{doc_name} 文档AI合规预审结果"
        # 4.1 纯文本部分（Markdown 原文）
        plain_body = table_md

        # 4.2 HTML 部分（将 Markdown 换行转 <br>）、
        html_body = markdown.markdown(
            table_md,
            extensions=[
                'tables',      # 支持表格
                'nl2br',       # 自动将换行转换为<br>
                'fenced_code',  # 支持代码块
                'md_in_html'   # 允许混合Markdown和HTML
            ],
            output_format='html'
        )
        
        # 包裹HTML结构并添加基本样式
        html_message = f"""<!DOCTYPE html>
<html>
<head>
<style>
table {{
    border-collapse: collapse;
    width: 100%;
    margin: 1em 0;
}}
th, td {{
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}}
th {{
    background-color: #f2f2f2;
}}
code {{
    background-color: #f5f5f5;
    padding: 2px 4px;
    border-radius: 3px;
}}
pre {{
    background-color: #f5f5f5;
    padding: 1em;
    overflow: auto;
}}
</style>
</head>
<body>
{html_body}
</body>
</html>"""

        msg = EmailMessage()
        msg['From']    = settings.smtp_sender
        msg['To']      = email
        msg['Subject'] = subject

        # 设置纯文本内容
        msg.set_content(plain_body)
        # 添加 HTML 备用内容
        msg.add_alternative(html_message, subtype='html')

        # 5. 调试输出：打印邮件内容
#        print("=== 准备发送邮件 ===")
#        print("Subject:", subject)
#        print("To     :", email)
#        print("Plain  :\n", plain_body)
#        print("HTML   :\n", html_message)
#        print("====================")

        # 6. 发送邮件（465 SSL 端口）
        try:
            with smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port) as server:
                server.login(settings.smtp_user, settings.smtp_pass)
                server.send_message(msg)
            print("邮件发送成功")
        except Exception as e:
            print("SMTP 发送失败：", repr(e))
            raise

    finally:
        # 7. 清理临时文件
        if os.path.exists(file_path):
            os.remove(file_path)
